package com.bilicraft.plugin.kexue;

import java.util.HashMap;
import java.util.Map;

import org.bukkit.Bukkit;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;

import com.bilicraft.plugin.kexue.utils.ExTimer;

public class CommandParser {
	
	/** Contains users accessed the plug functions since enable*/
	public static Map<String, ShellUser> userTable = new HashMap<String, ShellUser>();
	
	/** get current user with Player's name*/
	public static ShellUser getUser(CommandSender sender){
		if(sender instanceof Player){
			Player pl = (Player) sender;
			ShellUser user = userTable.get(pl.getName());
			if(user == null){
				user = new ShellUser(pl.getName());
				userTable.put(user.user, user);
			}
			return user;
		}else{
			ShellUser user = userTable.get("Console");
			if(user == null){
				user = new ShellUser("Console");
				userTable.put(user.user, user);
			}
			return user;
		}
	}
	
	/** dispatch commands*/
	public static boolean cmd(CommandSender sender, Command cmd, String label, String[] args){
		
		ShellUser user = getUser(sender);
		sender.sendMessage("["+user.user+"@bilicraft "+user.curdir+"]"+cmd.getName());
		if(cmd.getName().startsWith("_")){
			return user.shell.exec(sender, cmd, label, args);
		}else if(cmd.getName().equalsIgnoreCase("bbs")){
			sender.sendMessage("Shell users:");
			for(String s:userTable.keySet()){
				sender.sendMessage("- "+s);
			}
			sender.sendMessage("Timer state:"+ExTimer.getTimer().getState());
			sender.sendMessage("Timer isAlive:"+ExTimer.getTimer().isAlive());
			sender.sendMessage("If Timer alive, messages will be logged into console.");
			ExTimer.getInstance().trace = true;
    		return true;
    	}else if(cmd.getName().equalsIgnoreCase("biliblackscience")){
			Bukkit.getServer().dispatchCommand(sender, "help biliblackscience");
    		return true;
    	}
    	return false;
	}
}
